package com.yf.modules.security.service;

import cn.hutool.core.util.StrUtil;
import com.yf.Utils.RedisUtils;
import com.yf.configuration.SecurityProperties;
import com.yf.modules.security.model.dto.JwtUserDto;
import com.yf.modules.security.model.dto.OnlineUserDto;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author chentianwei
 * @date 2023/5/4 14:34
 * @description 在线用户服务
 */
@Service
@Slf4j
public class OnlineUserService {

    private final SecurityProperties properties;
    private final RedisUtils redisUtils;

    @Value("${login.user-cache.idle-time}")
    private long idleTime;

    public OnlineUserService(SecurityProperties properties,
                             RedisUtils redisUtils) {
        this.properties = properties;
        this.redisUtils = redisUtils;
    }

    /**
     * 查询用户
     *
     * @param key /
     * @return /
     */
    public OnlineUserDto getOne(String key) {
        return (OnlineUserDto) redisUtils.get(key);
    }

    /**
     * 在线用户缓存保存
     *
     * @param jwtUserDto 已认证用户信息
     * @param token      令牌
     * @param request    请求
     */
    public void UserCacheSave(JwtUserDto jwtUserDto, String token, HttpServletRequest request) {
        OnlineUserDto onlineUserDto = null;
        try {
            onlineUserDto = new OnlineUserDto(jwtUserDto.getUsername(),
                    jwtUserDto.getUser().getNickName(),
                    null, null, null, null, token, new Date());
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        redisUtils.set(properties.getOnlineKey() + token, onlineUserDto, properties.getTokenValidityInSeconds());
    }

    /**
     * 清理用户缓存信息
     * 用户信息变更时
     *
     * @param userName 用户名
     */
    @Async
    public void cleanUserCache(String userName) {
        if (StrUtil.isNotEmpty(userName)) {
            // 清除数据
            redisUtils.hashDel(SecurityProperties.cacheKey, userName);
        }
    }


}
